import axios, { AxiosInstance } from 'axios'
import qs from 'qs'
import merge from 'lodash/merge'
import { getToken } from './index'


export interface Http extends AxiosInstance {
    adornUrl: (url: string) => string
    adornParams: (params: object, openDefultParams?: boolean) => void
    adornData: (params: object, openDefultParams?: boolean) => void
}
// eslint-disable-next-line
const win = window as any

const http = axios.create({
    timeout: 30 * 1000,
    withCredentials: true,
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    }
}) as Http

/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
    if (config.url?.split('/').includes('login')) {
        config.headers['Authorization'] = '' // 请求头带上token
    } else {
        config.headers['Authorization'] = getToken() // 请求头带上token
    }
    return config
}, error => {
    return Promise.reject(error)
})

// let resFlag = false
/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
    if (response.data.code === 401) {
        sessionStorage.clear()
        location.reload()
    }
    return response
}, error => {
    return Promise.reject(error)
})

/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
http.adornUrl = (actionName: string) => {
    // 非生产环境 && 开启代理, 接口前缀统一使用[/proxy/]前缀做代理拦截!
    ////console.log(process.env.NODE_ENV)
    return (process.env.NODE_ENV !== 'production' ? '/api' : win.SITE_CONFIG.baseUrl) + actionName
}

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
http.adornParams = (params = {}, openDefultParams = true) => {
    const defaults = {
        't': new Date().getTime()
    }

    return openDefultParams ? merge(defaults, params) : params
}

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
http.adornData = (data = {}, openDefultdata = true, contentType = 'json') => {
    const defaults = {
        't': new Date().getTime()
    }
    data = openDefultdata ? merge(defaults, data) : data
    return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}


export default http
